package com.example.coreshopapp.utils;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.bean.OrderReq;
import com.sunmi.peripheral.printer.InnerPrinterCallback;
import com.sunmi.peripheral.printer.InnerPrinterException;
import com.sunmi.peripheral.printer.InnerResultCallback;
import com.sunmi.peripheral.printer.InnerPrinterManager;
import com.sunmi.peripheral.printer.SunmiPrinterService;

import android.os.RemoteException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DecimalStyle;
import java.util.List;

import bean.OrderBean;
import bean.OrderItemBean;

public class SunmiPrinterHelper {
    private static final String TAG = "SunmiPrinter";
    private SunmiPrinterService mPrinterService; // 打印机服务实例
    private Context mContext;
    private InnerPrinterCallback mPrinterCallback; // 服务连接回调

    public SunmiPrinterHelper(Context context) {
        this.mContext = context;
        initPrinterCallback();
    }

    // 初始化服务连接回调
    private void initPrinterCallback() {
        mPrinterCallback = new InnerPrinterCallback() {
            @Override
            protected void onConnected(SunmiPrinterService service) {
                // 服务连接成功，获取服务实例
                mPrinterService = service;
                Log.d(TAG, "打印机服务已连接");
                Toast.makeText(mContext, "打印机服务已连接", Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onDisconnected() {
                // 服务断开
                mPrinterService = null;
                Log.d(TAG, "打印机服务已断开");
                Toast.makeText(mContext, "打印机服务已断开", Toast.LENGTH_SHORT).show();
            }
        };
    }

    // 绑定打印机服务
    public void bindPrinterService() {
        try {
            boolean isBound = InnerPrinterManager.getInstance().bindService(mContext, mPrinterCallback);
            if (!isBound) {
                Log.e(TAG, "绑定打印机服务失败");
                Toast.makeText(mContext, "绑定打印机服务失败", Toast.LENGTH_SHORT).show();
            }
        } catch (InnerPrinterException e) {
            Log.e(TAG, "绑定服务异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 打印文本内容
    public void printText(String content) {
        if (mPrinterService == null) {
            Toast.makeText(mContext, "打印机服务未连接", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            // 调用打印文本方法，添加换行符确保内容完整
            mPrinterService.printText(content + "", new InnerResultCallback() {
                @Override
                public void onRunResult(boolean isSuccess) throws RemoteException {
                    Log.d(TAG, "接口执行结果: " + (isSuccess ? "成功" : "失败"));
                }

                @Override
                public void onReturnString(String result) throws RemoteException {
                    Log.d(TAG, "返回数据: " + result);
                }

                @Override
                public void onRaiseException(int code, String msg) throws RemoteException {
                    Log.e(TAG, "执行异常 - 代码: " + code + ", 信息: " + msg);
                    Toast.makeText(mContext, "打印异常: " + msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPrintResult(int code, String msg) throws RemoteException {
                    // 真实打印结果
                    Log.d(TAG, "打印结果 - 代码: " + code + ", 信息: " + msg);
                    if (code == 0) {
                        Toast.makeText(mContext, "打印成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(mContext, "打印失败: " + msg, Toast.LENGTH_SHORT).show();
                    }
                    // 打印完成后断开服务（根据需求决定是否立即断开）
                    unbindPrinterService();
                }
            });
        } catch (RemoteException e) {
            Log.e(TAG, "打印调用异常: " + e.getMessage());
            e.printStackTrace();
            Toast.makeText(mContext, "打印失败，请检查设备支持", Toast.LENGTH_SHORT).show();
        }
    }




    // 断开打印机服务
    public void unbindPrinterService() throws InnerPrinterException {
        if (mPrinterCallback != null) {

            InnerPrinterManager.getInstance().unBindService(mContext, mPrinterCallback);

            Log.d(TAG, "已断开打印机服务");

        }
    }

    public void printOrder(OrderBean orderData) {
        if (mPrinterService == null) {
            Toast.makeText(mContext, "打印机服务未连接", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedNow = now.format(formatter);
            orderData.setCreateTime(formattedNow);
            // 1. 打印标题（居中，大字体）
            setAlignment(1); // 1=居中对齐（0=左对齐，2=右对齐）
            setFontSize(30f, null); // 标题字体稍大
            printText(Constants.AppConstVars.sysUser.getStoreName() + "\n");

            // 2. 订单号（左对齐，默认字体）
            setAlignment(0); // 左对齐
            setFontSize(30f, null); // 内容字体
            printText("单号：" + orderData.getOrderId() + "\n");

            setFontSize(30f, null); // 内容字体
            printText("日期：" +orderData.getCreateTime() + "\n");
            printText("-------------------------" + "\n");
            // 3. 商品明细标题行（左对齐，加粗效果用换行+重复文本模拟）
            printText("品名   原价   数量   金额" + "\n");
            printText("-------------------------" + "\n");


            //折扣金额

            BigDecimal discountAmount = BigDecimal.ZERO;
            BigDecimal allAmount =BigDecimal.ZERO;
            // 4. 循环打印商品明细（左对齐，多列对齐）
            List<OrderItemBean> goodsList = orderData.getItems();
            if (goodsList != null && !goodsList.isEmpty()) {
                for (OrderItemBean item : goodsList) {
                    // 商品名称（左对齐，最多10个汉字，超出截断）
                    String name = item.getName();
                    setFontSize(28,null);
                    printText(name+ "\n");
                    // 用空格补位，确保列对齐（等宽字体下有效）
                    String line = String.format("%12s %4s %8s",
                            item.getMktprice(), // 数量（右对齐，占6字符）
                            item.getNums(), // 单价（右对齐，占8字符）
                            item.getMktprice()*item.getNums()); // 原价（右对齐，占8字符）
                    printText(line + "\n");

                    // 计算单条记录的金额差
                    BigDecimal mktPrice = BigDecimal.valueOf(item.getMktprice()); // 市场价
                    BigDecimal nums = BigDecimal.valueOf(item.getNums());         // 数量
                    BigDecimal amount = mktPrice.multiply(nums);                  // 原价总额 = 市场价 * 数量
                    BigDecimal itemAmount = BigDecimal.valueOf(item.getAmount()); // 实际金额
                    BigDecimal diff = amount.subtract(itemAmount);                // 差价 = 原价总额 - 实际金额
                    discountAmount = discountAmount.add(diff).setScale(2, RoundingMode.HALF_UP);
                    allAmount = allAmount.add(amount).setScale(2, RoundingMode.HALF_UP);
                }
            } else {
                printText("无商品明细" + "\n");
            }
            setFontSize(30f,null);
            // 5. 分割线
            printText("-------------------------" + "\n");

            //件数
            int totalCount = goodsList.stream()
                    .mapToInt(OrderItemBean::getNums) // 提取age字段，转换为IntStream
                    .sum(); // 求和




            printText("件数:" +totalCount+ "  合计:"+allAmount+"\n");

            // 6. 折扣金额（右对齐，突出显示）
            setAlignment(0); // 左对齐
            printText("折扣金额：" + discountAmount +"\n");

            // 6. 实付金额（右对齐，突出显示）
            setAlignment(0); // 左对齐
            printText("实收金额：" + orderData.getOrderAmount() +"\n");

            // 6. 支付金额（右对齐，突出显示）
            setAlignment(0); // 左对齐
            printText("支付金额：" + orderData.getOrderAmount() +"\n");
            setAlignment(0); // 左对齐

            //支付方
            int paymentId= orderData.getPaymentList().get(0).getPaymentId();
            if(paymentId==0)
                printText("现金：" + orderData.getPaymentList().get(0).getCashAmount() + "\n");
            else if(paymentId==5)
                printText("银行卡：" + orderData.getOrderAmount() + "\n");

            if(paymentId==0)
            {
                setAlignment(0); // 左对齐
                double zsAmount=orderData.getPaymentList().get(0).getCashAmount()-orderData.getOrderAmount();
                printText("找零：" + zsAmount+ "\n\n");
            }

            setFontSize(30f,null);
            setAlignment(1);
            printText("放心粮油在天润！" + "\n");
            setAlignment(1);
            printText("祝您购物愉快！" + "\n\n\n\n");
            // 9. 走纸（部分机型需要手动走纸）
            //mPrinterService.lineWrap(3); // 走3行

        } catch (RemoteException e) {
            Log.e(TAG, "打印订单异常: " + e.getMessage());
            e.printStackTrace();
            Toast.makeText(mContext, "打印失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    // 辅助方法：设置对齐方式（0=左对齐，1=居中，2=右对齐）
    private void setAlignment(int alignment) throws RemoteException {
        mPrinterService.setAlignment(alignment, new InnerResultCallback() {
            @Override
            public void onRunResult(boolean isSuccess) throws RemoteException {}
            @Override
            public void onReturnString(String result) throws RemoteException {}
            @Override
            public void onRaiseException(int code, String msg) throws RemoteException {}
            @Override
            public void onPrintResult(int code, String msg) throws RemoteException {}
        });
    }

    // 辅助方法：简化字体设置（忽略回调）
    private void setFontSize(float size, InnerResultCallback callback) throws RemoteException {
        if (callback == null) {
            callback = new InnerResultCallback() {
                @Override
                public void onRunResult(boolean isSuccess) throws RemoteException {}
                @Override
                public void onReturnString(String result) throws RemoteException {}
                @Override
                public void onRaiseException(int code, String msg) throws RemoteException {}
                @Override
                public void onPrintResult(int code, String msg) throws RemoteException {}
            };
        }
        mPrinterService.setFontSize(size, callback);
    }

    // 新增：设置行间距（单位：点，1点≈0.3527毫米）
    private void setLineSpacing(int spacing) throws RemoteException {
        if (mPrinterService == null) return;
        mPrinterService.setFontSize(10,null);
        mPrinterService.lineWrap(spacing, new InnerResultCallback() {
            @Override
            public void onRunResult(boolean isSuccess) throws RemoteException {}
            @Override
            public void onReturnString(String result) throws RemoteException {}
            @Override
            public void onRaiseException(int code, String msg) throws RemoteException {}
            @Override
            public void onPrintResult(int code, String msg) throws RemoteException {}
        });
    }
    public  boolean isSunmiDeviceByManufacturer() {
        // 获取设备制造商信息（可能为小写，建议转大写后判断）
        String manufacturer = Build.MANUFACTURER;
        return manufacturer != null && manufacturer.trim().equalsIgnoreCase("Sunmi");
    }
}